<template>
  <div class="channel-edit">
    <van-cell :border="false">
      <div slot="title">我的频道</div>
      <van-button
        size="mini"
        round
        type="danger"
        plain
        @click="isEdit = !isEdit"
        >{{ isEdit ? '完成' : '编辑' }}</van-button
      >
    </van-cell>
    <van-grid :gutter="10">
      <van-grid-item
        icon="clear"
        class="grid-item"
        v-for="(channel, index) in myChannels"
        :key="index"
        @click="onMyChannelClick(channel, index)"
      >
        <van-icon
          v-show="isEdit && !fiexdChannels.includes(channel.id)"
          slot="icon"
          name="clear"
        ></van-icon>
        <span
          class="text"
          :class="{ active: index === activeIndex }"
          slot="text"
          >{{ channel.name }}</span
        >
      </van-grid-item>
    </van-grid>
    <van-cell :border="false">
      <div slot="title">频道推荐</div>
    </van-cell>
    <van-grid :gutter="10">
      <van-grid class="recomment-grid" :gutter="10">
        <van-grid-item
          icon="plus"
          class="grid-item"
          v-for="channel in recommendChannele"
          :key="channel.id"
          :text="channel.name"
          @click="onAddChannel(channel)"
        />
      </van-grid>
    </van-grid>
  </div>
</template>

<script>
import { getAllChannels, addUserChannel, deletUserChannle } from '@/api/channel'
import { mapState } from 'vuex'
import { setItem } from '@/utils/storage'
export default {
  name: 'ChannelEdit',
  props: {
    myChannels: { type: Array, required: true },
    activeIndex: { type: Number, required: true }
  },
  data () {
    return {
      allChannels: [],
      isEdit: false, // 控制编辑状态
      fiexdChannels: [0] // 不需要编辑、删除的频道
    }
  },
  created () {
    this.loadAllChannels()
  },
  mounted () {},
  methods: {
    //   获取全部频道
    async loadAllChannels () {
      try {
        const { data } = await getAllChannels()
        console.log(data)
        this.allChannels = data.data.channels
      } catch (err) {
        console.log(err)
        this.$toast('获取所有频道数据失败')
      }
    },
    // 添加频道
    async onAddChannel (channel) {
      this.myChannels.push(channel)
      // 数据持久化处理
      if (this.user) {
        try {
          await addUserChannel({
            id: channel.id,
            seq: this.myChannels.length
          })
        } catch (err) {
          console.log(err)
        }
      } else {
        setItem('TOUTIAO_CHANNELS', this.myChannels)
      }
    },
    // 切换和删除
    onMyChannelClick (channel, index) {
      // 点击isEdit为true时是删除功能
      // 反之为切换功能
      if (this.isEdit) {
        // 如果是fiexdChannels中保存的则者直接跳出，不执行删除功能
        if (this.fiexdChannels.includes(channel.id)) {
          return true
        }
        // 传入索引通过splice方法删除
        this.myChannels.splice(index, 1)
        // 如果删除的是在选中的前面的元素就减一保证能继续选中本元素，如果是本元素则传给下一个元素
        if (index <= this.activeIndex) {
          this.$emit('update-active', this.activeIndex - 1, true)
        }

        this.deleteChannel(channel)
      } else {
        // 将索引传递给父组件，改变父组件力active的值来达到切换的功能
        this.$emit('update-active', index, false)
      }
    },
    // 删除数据
    async deleteChannel (channel) {
      try {
        if (this.user) {
          await deletUserChannle(channel.id)
        } else {
          setItem('TOUTIAO_CHANNELS', this.myChannels)
        }
      } catch (err) {
        console.log(err)
      }
    }
  },
  computed: {
    ...mapState(['user']),
    // 计算属性会检测数据
    // 当数据发生变化时，计算属性也会改变
    recommendChannele () {
      // 筛选出推荐频道的数据
      const channels = []
      //   通过forEach循环在遍历allChannels 符合条件的就筛选出来
      this.allChannels.forEach(channel => {
        const ret = this.myChannels.find(myChannels => {
          return myChannels.id === channel.id
        })
        // 如果我的频道中不包括该频道项，则收集到推荐频道中
        if (!ret) {
          channels.push(channel)
        }
      })
      return channels
    }
  }
}
</script>

<style scoped lang="less">
.channel-edit {
  padding: 85px 0;
  .title-text {
    font-size: 32px;
    color: #333;
  }
  .edit-btn {
    width: 104px;
    height: 48px;
    font-size: 26px;
    color: #f85959;
    border: 1px solid #f85959;
  }
  /deep/ .grid-item {
    width: 160px;
    height: 86px;
    .van-grid-item__content {
      white-space: nowrap;
      background-color: #f4f5f6;
      .van-grid-item__text,
      .text {
        font-size: 22px;
        color: #222;
        margin-top: 4px !important;
      }
      .active {
        color: red;
      }
    }
  }

  /deep/ .grid-item {
    .van-icon-clear {
      position: absolute;
      top: -34px;
      right: -90px;
      font-size: 30px;
      color: #cacaca;
      z-index: 2;
    }
  }
  //   .van-grid-item__icon-wrapper {
  //     position: unset;
  //   }

  /deep/ .recomment-grid {
    .grid-item {
      width: 160px;
      height: 86px;
      .van-grid-item__content {
        flex-direction: row;
        .van-icon-plus {
          font-size: 22px;
          line-height: 22px;
          margin-right: 6px;
        }
      }
    }
  }
}
</style>
